package com.example.partner.adapter.find;

import static android.content.ContentValues.TAG;
import static android.content.Context.MODE_PRIVATE;
import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.partner.R;
import com.example.partner.activity.find.PostDetailActivity;
import com.example.partner.activity.home.UserInfoActivity;
import com.example.partner.common.BaseResponse;
import com.example.partner.model.domain.Post;
import java.util.List;
import com.bumptech.glide.Glide;
import com.example.partner.service.FollowService;
import com.example.partner.service.PostService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {

    private List<Post> postList;
    private Context context;

    private Long userId;


    public PostAdapter(List<Post> postList, Context context) {
        this.postList = postList;
        this.context = context;
    }

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post, parent, false);
        return new PostViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        Post post = postList.get(position);
        SharedPreferences sharedPreferences = context.getSharedPreferences("CurrentUser", MODE_PRIVATE);
        userId = sharedPreferences.getLong("userId", -1);
        // 设置帖子项的内容
        holder.textViewTitle.setText(post.getTitle());
        holder.textViewAuthor.setText(post.getName());
        holder.textViewTime.setText(post.getCreateTime().toString());
        Boolean isLiked = post.getLike();
        holder.imageViewLike.setImageResource(isLiked != null && isLiked ? R.drawable.ic_like_hightlight : R.drawable.ic_like);
        holder.textViewLikeCount.setText(String.valueOf(post.getLiked()));
        holder.textViewCommentCount.setText(String.valueOf(post.getComments()));
        Glide.with(context).load(post.getAvatar()).placeholder(R.drawable.placeholder_avatar).into(holder.imageViewAuthor);
        // 设置帖子的第一张图片，这里假设有多张图片用逗号分隔
        String[] images = post.getAvatarUrl() != null ? post.getAvatarUrl().split(",") : new String[0];
        // 如果有图片就加载第一张
        if (images.length > 0) {
            // 使用你的图片加载库加载图片，这里用占位符代替
             Glide.with(context).load(images[0]).placeholder(R.drawable.placeholder_image).into(holder.imageViewPost);
        }
        // 设置帖子项的点击事件，跳转到帖子详情页
        holder.imageViewPost.setOnClickListener(v -> {
            // 获取当前帖子的ID（假设你的帖子类中有一个getId()方法）
            // 创建 Intent，并传递帖子的ID到 PostDetailActivity
            Intent intent = new Intent(context, PostDetailActivity.class);
            intent.putExtra("postId", post.getId());
            // 启动帖子详情页
            context.startActivity(intent);
        });
        // 点赞图标的点击事件
        holder.imageViewLike.setOnClickListener(v -> {
            // 获取当前帖子的点赞状态
            boolean currentLikeState = post.getLike() != null && post.getLike();
            // 更新图标和点赞数量
            if (currentLikeState) {
                // 取消点赞
                post.setLike(false);
                post.setLiked(post.getLiked() - 1);
            } else {
                // 点赞
                post.setLike(true);
                post.setLiked(post.getLiked() + 1);
            }
            likePost(post.getId(),userId);
            // 刷新列表项
            notifyItemChanged(position);
        });
    }


    private void likePost(Long id,Long userId){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PostService postService = retrofit.create(PostService.class);
        Call<BaseResponse<Boolean>> call = postService.likePost(id,userId);
        call.enqueue(new Callback<BaseResponse<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResponse<Boolean>> call, Response<BaseResponse<Boolean>> response) {

            }

            @Override
            public void onFailure(Call<BaseResponse<Boolean>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });
    }

    @Override
    public int getItemCount() {
        if (postList==null){
            return 0;
        }
        return postList.size();
    }

    public static class PostViewHolder extends RecyclerView.ViewHolder {
        TextView textViewTitle, textViewAuthor, textViewTime, textViewLikeCount, textViewCommentCount;
        ImageView imageViewPost, imageViewAuthor, imageViewLike, imageViewComment;
        Button buttonFollow;

        public PostViewHolder(@NonNull View itemView) {
            super(itemView);
            textViewTitle = itemView.findViewById(R.id.textViewTitle);
            textViewAuthor = itemView.findViewById(R.id.textViewAuthor);
            textViewTime = itemView.findViewById(R.id.textViewTime);
            textViewLikeCount = itemView.findViewById(R.id.textViewLikeCount);
            textViewCommentCount = itemView.findViewById(R.id.textViewCommentCount);
            imageViewPost = itemView.findViewById(R.id.imageViewPost);
            imageViewAuthor = itemView.findViewById(R.id.imageViewAuthor);
            imageViewLike = itemView.findViewById(R.id.imageViewLike);
            imageViewComment = itemView.findViewById(R.id.imageViewComment);
            buttonFollow = itemView.findViewById(R.id.buttonFollow);
        }
    }
}
